package com.app.markdown.handler;

import com.app.markdown.store.FileStore;
import com.app.markdown.util.FileUtil;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

/**
 * @Author 56465
 * @Create 2024/7/30 17:27
 */
public class ListenerHandler {
    /**
     * 文字监听
     * @param fileContentArea
     */
    public static void addTextListener(WebView webView) {
        WebEngine webEngine = webView.getEngine();
        webEngine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
            if (newState == javafx.concurrent.Worker.State.SUCCEEDED) {
                System.out.println("HTML内容已加载");
                // 使用JavaScript监听WebView的点击事件，并创建一个新的<p>标签
                webEngine.executeScript("function addClickEventListener() {"
                        + "document.body.addEventListener('click', function(event) {"
                        + "  var p = document.createElement('p');"
                        + "  p.contentEditable = 'true';"
                        + "  document.body.appendChild(p);"
                        + "  var range = document.createRange();"
                        + "  range.selectNodeContents(p);"
                        + "  range.collapse(true);"
                        + "  var sel = window.getSelection();"
                        + "  sel.removeAllRanges();"
                        + "  sel.addRange(range);"
                        + "});"
                        + "}"
                        + "addClickEventListener();");
            }
        });
    }

    /**
     * 添加键盘快捷键监听
     */
    public void addKeyboardListener(Node rootVBox) {
        // 获取当前场景
        Scene scene = rootVBox.getScene();
        if (scene != null) {
            // 添加键盘事件监听器
            scene.setOnKeyPressed(this::handleKeyPressEvent);
        }
    }
    private void handleKeyPressEvent(KeyEvent keyEvent) {
        // 检查是否按下了 Ctrl+S
        if (keyEvent.isControlDown() && keyEvent.getCode() == KeyCode.S) {
            keyEvent.consume(); // 防止默认行为
            FileUtil.saveFileContent(FileStore.currentFilePathName);
        }
    }
}
